package guava;

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.primitives.Doubles;
import org.junit.Test;

import java.util.Comparator;
import java.util.List;

/**
 * Ordering：用于排序的比较器
 * User: Realfighter
 * Date: 2014/10/19
 * Time: 23:46
 */
public class OrderingTest {

    @Test
    public void testOrdering() {
        //虚拟三个double值，用于下面的比较和排序
        Double first = 0.1;
        Double[] second = {0.2, 0.3};
        List<Double> numbers = Lists.asList(first, second);
        //排序比较器：根据原始的大小排序
        Ordering<Double> peopleOrdering = new Ordering<Double>() {
            @Override
            public int compare(Double left, Double right) {
                return Doubles.compare(left, right);
            }
        };
        //自定义比较器：根据1除以原始值后得到的值的大小排序
        Comparator<Double> comparator = new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return Doubles.compare(1 / o1, 1 / o2);
            }
        };
        //sortedCopy:对传入的集合进行Ordering排序比较
        peopleOrdering.sortedCopy(numbers); //[0.1, 0.2, 0.3]

        //reverse:对Ordering进行反向排序
        peopleOrdering.reverse().sortedCopy(numbers);//[0.3, 0.2, 0.1]

        //from:根据传入comparator作为排序的比较器
        peopleOrdering.from(comparator).sortedCopy(numbers); //[0.3, 0.2, 0.1]
        peopleOrdering.from(comparator).reverse().sortedCopy(numbers);//[0.1, 0.2, 0.3]

        //isOrdered:根据Ordering对传入iterable元素迭代，如果下一个元素大于或等于上一个元素，返回true
        peopleOrdering.isOrdered(numbers);//true
        peopleOrdering.from(comparator).isOrdered(numbers);//false

        //explicit:根据传入对象的顺序排序
        peopleOrdering.reverse().explicit(numbers).sortedCopy(numbers);//[0.1, 0.2, 0.3]

        //arbitrary:返回所有对象任意顺序
        peopleOrdering.arbitrary().sortedCopy(numbers);

        //compound: 返回一个Ordering，comparator作为第二排序元素
        peopleOrdering.reverse().compound(comparator).sortedCopy(numbers); //[0.3, 0.2, 0.1]

        //其他比较简单的方法，如：nullsFirst，nullsLast，min，max，leastOf，greatestOf这里不再赘述。

        //其余重要的方法：lexicographical，binarySearch 未完待续...
    }

}
